import React from 'react';
import { Card, Row, Col, Space, Button, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import EditForm from './components/EditForm';
import Access from './components/Access';
import { update, detail } from '@/services/Role';
import { history } from 'umi';

class Detail extends React.Component {

  constructor(props) {
    super(props);
    this.id = props.location.query.id;
    this.formRef = React.createRef();
    this.state = {
      isLoading: false,
      menuId: []
    };
  }

  /* 获取详情 */
  getDetail = async () => {
    try {
      const id = this.id;
      if (!id) throw new Error('非法请求！');
      const { setFieldsValue } = this.formRef.current;
      const res = await detail(id);
      const { name, describe } = res;
      setFieldsValue({ name, describe });
    } catch (e) {
      !e.code && e.message ? message.error(e.message) : null;
    }
  }

  /* 重置 */
  onReset = () => {
    const { resetFields } = this.formRef.current;
    resetFields();
  }

  /* 确认 */
  onConfirm = async () => {
    try {
      const id = this.id;
      if (!id) throw new Error('非法请求！');
      const { validateFields } = this.formRef.current;
      const { menuId } = this.state;
      const values = await validateFields();
      this.setState({ isLoading: true });
      await update({ ...values, id, menuId });
      message.success('修改成功！');
      setTimeout(function () { history.goBack() }, 1500)
    } catch (e) {
      !e.code && e.message ? message.error(e.message) : null;
    } finally {
      this.setState({ isLoading: false });
    }
  }

  /* 权限选择 */
  onAccessCheck = (checked) => {
    this.setState({ menuId: checked })
  }

  componentDidMount() {
    this.getDetail();
  }

  render() {
    const { onConfirm, onReset, onAccessCheck, formRef, id } = this;
    const { isLoading } = this.state;
    return (
      <PageContainer>
        <Card
          title='修改内容'
          bodyStyle={{ paddingTop: 48, paddingBottom: 48 }}
          bordered={false}>
          <div style={{ width: '70vw' }}>
            <EditForm ref={formRef} />
            <Row style={{ marginBottom: 24 }}>
              <Col span={6} style={{ textAlign: 'right' }}>权限分配：</Col>
              <Col span={12}>
                <Access id={id} check={onAccessCheck} />
              </Col>
            </Row>
            <Row>
              <Col span={6}></Col>
              <Col span={6}>
                <Space>
                  <Button onClick={() => { history.goBack() }}>取消</Button>
                  <Button onClick={onReset}>重置</Button>
                  <Button loading={isLoading} type="primary" onClick={onConfirm}>确定</Button>
                </Space>
              </Col>
            </Row>
          </div>
        </Card>
      </PageContainer>
    );
  }
}

export default Detail;
